package edu.yctc.manage.controller;

import edu.yctc.manage.constant.RequestAttributes;
import edu.yctc.manage.constant.TemplatePath;
import edu.yctc.manage.entity.ResultDO;
import edu.yctc.manage.entity.UserDO;
import edu.yctc.manage.service.UserService;
import edu.yctc.manage.vo.AdminSignInVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * @ClassName IndexController
 * @Description TODO
 * @Author zyj
 * @Date 2021/3/29 14:49
 * @Version 1.0
 **/
@Controller
public class IndexController {

    @Autowired
    private UserService userService;

    @GetMapping({TemplatePath.S, TemplatePath.S + TemplatePath.INDEX, TemplatePath.S + TemplatePath.INDEX_HTML})
    public String showIndex() {
        return TemplatePath.INDEX;
    }

    @PostMapping(TemplatePath.S + TemplatePath.SIGN_IN)
    public String signIn(@ModelAttribute AdminSignInVO adminSignInVO, HttpSession httpSession) {
        // 入参核验
        if (StringUtils.isBlank(adminSignInVO.getAccount()) || StringUtils.isBlank(adminSignInVO.getPassword())) {
            httpSession.setAttribute(RequestAttributes.ERROR_MSG, RequestAttributes.MSG_ACCOUNT_PASSWORD_CANNOT_EMPTY);
            return TemplatePath.INDEX;
        }
        // 核验验证码
        String kaptcha = httpSession.getAttribute("verifyCode") + "";
        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(adminSignInVO.getVerifyCode())
            || adminSignInVO.getVerifyCode().equals(kaptcha) == false) {
            httpSession.setAttribute(RequestAttributes.ERROR_MSG, RequestAttributes.MSG_ERROR_VERIFY_CODE);
            return TemplatePath.INDEX;
        }
        UserDO userDO = new UserDO();
        userDO.setPassword(adminSignInVO.getPassword());
        userDO.setAccount(adminSignInVO.getAccount());
        ResultDO resultDO = userService.signIn(userDO);
        if (Integer.parseInt(resultDO.get("code").toString()) != 0) {
            httpSession.setAttribute(RequestAttributes.ERROR_MSG, resultDO.get("msg").toString());
            return TemplatePath.INDEX;
        }
        return "redirect:/" + TemplatePath.ADMIN_INDEX;
    }

    @GetMapping(TemplatePath.ADMIN_INDEX)
    public String showAdminIndex(){
        return TemplatePath.ADMIN_INDEX;
    }
}
    